package com.lzf.trace.modules.manage.avtivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.huawei.agconnect.AGCRoutePolicy;
import com.huawei.agconnect.AGConnectInstance;
import com.huawei.agconnect.AGConnectOptions;
import com.huawei.agconnect.AGConnectOptionsBuilder;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectUser;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList;
import com.huawei.agconnect.cloud.database.CloudDBZoneQuery;
import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.lzf.trace.IBaseActivity;
import com.lzf.trace.R;
import com.lzf.trace.modules.manage.dto.AddEvent;
import com.lzf.trace.modules.manage.dto.ObjectTypeInfoHelper;
import com.lzf.trace.modules.manage.dto.Product;
import com.lzf.trace.publics.utils.L;
import com.lzf.trace.publics.utils.T;
import com.qmuiteam.qmui.recyclerView.QMUIRVItemSwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeViewHolder;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ProductListActivity extends IBaseActivity {

    AGConnectCloudDB mCloudDB;
    CloudDBZoneConfig mConfig;
    CloudDBZone mCloudDBZone;

    private static String countryCodeStr = "86";

    private QMUITopBar mTopbar;
    private QMUIPullLayout mPullLayout;
    private RecyclerView mRecyclerView;
    private Adapter mAdapter;

    private Button add_btn;

    private Integer maxId = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);
        EventBus.getDefault().register(this);

        initViews();
        initDatas();
    }


    @Override
    public void initViews() {

        mTopbar = findViewById(R.id.topbar);
        mPullLayout = findViewById(R.id.pull_layout);
        mRecyclerView = findViewById(R.id.recyclerView);
        mTopbar.setTitle("全部溯源信息");
        mTopbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTopbar.addRightTextButton("注销登录", R.id.topbar_right_about_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AGConnectAuth.getInstance().signOut();
                finish();
            }
        });

        add_btn = findViewById(R.id.add_btn);
        add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, AddActivity.class));
            }
        });

    }

    @Override
    public void initDatas() {
        AGConnectUser user = AGConnectAuth.getInstance().getCurrentUser();
        if (user == null) {
            finish();
        }

        mPullLayout.setActionListener(new QMUIPullLayout.ActionListener() {
            @Override
            public void onActionTriggered(@NonNull final QMUIPullLayout.PullAction pullAction) {
                mPullLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                            onRefreshData();
                        } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                            onLoadMore();
                        }
                        mPullLayout.finishActionRun(pullAction);
                    }
                }, 3000);
            }
        });

        QMUIRVItemSwipeAction swipeAction = new QMUIRVItemSwipeAction(true, new QMUIRVItemSwipeAction.Callback() {
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                mAdapter.remove(viewHolder.getAdapterPosition());
            }

            @Override
            public int getSwipeDirection(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return QMUIRVItemSwipeAction.SWIPE_LEFT;
            }

            @Override
            public void onClickAction(QMUIRVItemSwipeAction swipeAction, RecyclerView.ViewHolder selected, QMUISwipeAction action) {
                super.onClickAction(swipeAction, selected, action);
//                T.showShort(mContext, "你点击了第 " + selected.getAdapterPosition() + " 个 item 的" + action.getText());
                if (action == mAdapter.mDeleteAction) {
                    Product mProduct = mAdapter.getItems().get(selected.getAdapterPosition());
                    deleteBookInfosAsync(mProduct);
                    mAdapter.remove(selected.getAdapterPosition());
                }
                if (action == mAdapter.mWriteReviewAction) {
                    Product mProduct = mAdapter.getItems().get(selected.getAdapterPosition());
                    Intent intent = new Intent(mContext, AddActivity.class);
                    Gson mGson = new Gson();
                    String intentData = mGson.toJson(mProduct);
                    intent.putExtra("product_item", intentData);
                    startActivity(intent);
                } else {
                    swipeAction.clear();
                }
            }
        });
        swipeAction.attachToRecyclerView(mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });

        mAdapter = new Adapter(mContext);
        mRecyclerView.setAdapter(mAdapter);

        initCloudDatabase();

//        getData();
    }


    private void getData() {
        CloudDBZoneQuery<Product> query = CloudDBZoneQuery.where(Product.class).orderByDesc("id");
        queryPersonInfo(query);
    }

    private void queryPersonInfo(CloudDBZoneQuery<Product> query) {
        if (mCloudDBZone == null) {
            return;
        }
        Task<CloudDBZoneSnapshot<Product>> queryTask = mCloudDBZone.executeQuery(query,
                CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
        //List<personInfo> tmpInfoList = new ArrayList<>();
        queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<Product>>() {
            @Override
            public void onSuccess(CloudDBZoneSnapshot<Product> snapshot) {
                processQueryResult(snapshot);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(final Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        T.showShort(mContext, "获取数据失败！" + e.toString());
                    }
                });
            }
        });
    }

    private void processQueryResult(CloudDBZoneSnapshot<Product> snapshot) {
        CloudDBZoneObjectList<Product> bookInfoCursor = snapshot.getSnapshotObjects();
        List<Product> bookInfoList = new ArrayList<>();
        try {
            while (bookInfoCursor.hasNext()) {
                Product bookInfo = bookInfoCursor.next();
                bookInfoList.add(bookInfo);
            }
        } catch (AGConnectCloudDBException e) {
            L.e("query data", "processQueryResult: " + e.getMessage());
        }
        snapshot.release();
//        T.showShort(mContext, "数据总量" + bookInfoList.size());
//        mUiCallBack.onAddOrQuery(bookInfoList);

        if (bookInfoList.size() > 0) {
            maxId = bookInfoList.get(0).getId();
            onDataLoaded(bookInfoList);
        }
    }

    private void onDataLoaded(List<Product> bookInfoList) {
        mAdapter.setData(bookInfoList);
    }

    private void onRefreshData() {
        getData();
    }

    private void onLoadMore() {

    }


    class Adapter extends RecyclerView.Adapter<QMUISwipeViewHolder> {

        private List<Product> mData = new ArrayList<>();

        final QMUISwipeAction mDeleteAction;
        final QMUISwipeAction mWriteReviewAction;

        public Adapter(Context context) {
            QMUISwipeAction.ActionBuilder builder = new QMUISwipeAction.ActionBuilder()
                    .textSize(QMUIDisplayHelper.sp2px(context, 14))
                    .textColor(Color.WHITE)
                    .paddingStartEnd(QMUIDisplayHelper.dp2px(mContext, 14));

            mWriteReviewAction = builder.text("编辑").backgroundColor(Color.DKGRAY).build();
            mDeleteAction = builder.text("删除").backgroundColor(Color.RED).build();
        }

        public void setData(@Nullable List<Product> list) {
            mData.clear();
            if (list != null) {
                mData.addAll(list);
            }
            notifyDataSetChanged();
        }

        public void remove(int pos) {
            mData.remove(pos);
            notifyItemRemoved(pos);
            notifyDataSetChanged();
        }

        public void add(int pos, Product item) {
            mData.add(pos, item);
            notifyItemInserted(pos);
        }

        public void prepend(@NonNull List<Product> items) {
            mData.addAll(0, items);
            notifyDataSetChanged();
        }

        public void append(@NonNull List<Product> items) {
            mData.addAll(items);
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public QMUISwipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
            final QMUISwipeViewHolder vh = new QMUISwipeViewHolder(view);
            vh.addSwipeAction(mDeleteAction);
            vh.addSwipeAction(mWriteReviewAction);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            return vh;
        }

        @Override
        public void onBindViewHolder(@NonNull QMUISwipeViewHolder holder, int position) {
            TextView title = holder.itemView.findViewById(R.id.title);
            title.setText(mData.get(position).getName());
            TextView factory = holder.itemView.findViewById(R.id.factory);
            factory.setText(mData.get(position).getFactory());
            TextView model = holder.itemView.findViewById(R.id.model);
            model.setText("规格:" + mData.get(position).getModel());
            TextView batch = holder.itemView.findViewById(R.id.batch);
            batch.setText("批号:" + mData.get(position).getBatch());
            TextView createtime = holder.itemView.findViewById(R.id.createtime);
            createtime.setText("生产日期:" + mData.get(position).getCreatetime());
            TextView endtime = holder.itemView.findViewById(R.id.endtime);
            endtime.setText("有效期至:" + mData.get(position).getEndtime());
            TextView code = holder.itemView.findViewById(R.id.code);
            code.setText("溯源码:" + mData.get(position).getCode());
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        public List<Product> getItems() {
            return mData;
        }
    }


    private void initCloudDatabase() {
        //初始化云数据库
        AGConnectCloudDB.initialize(getApplicationContext());
//        AGConnectOptions agcConnectOptions = new AGConnectOptionsBuilder().setRoutePolicy(AGCRoutePolicy.CHINA).build(mContext);
//        AGConnectInstance instance = AGConnectInstance.buildInstance(agcConnectOptions);
        AGConnectInstance instance = AGConnectInstance.getInstance();
        mCloudDB = AGConnectCloudDB.getInstance(instance, AGConnectAuth.getInstance(instance));
        try {
            mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
            mConfig = new CloudDBZoneConfig("trace",
                    CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
                    CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
            mConfig.setPersistenceEnabled(true);
            Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
            openDBZoneTask.addOnSuccessListener(new OnSuccessListener<CloudDBZone>() {
                @Override
                public void onSuccess(CloudDBZone cloudDBZone) {
                    L.i("open clouddbzone", "open cloudDBZone success");
                    mCloudDBZone = cloudDBZone;
                    //开始获取数据
                    getData();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    L.e("open clouddbzone", "open cloudDBZone failed for " + e.getMessage());
                }
            });
        } catch (AGConnectCloudDBException e) {
            T.showShort(mContext, "initialize CloudDB failed:" + e.toString());
        }

    }


    public void upsertProduct(Product product) {
        if (mCloudDBZone == null) {
            return;
        }
        Task<Integer> upsertTask = mCloudDBZone.executeUpsert(product);
        upsertTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
            @Override
            public void onSuccess(Integer cloudDBZoneResult) {
                T.showShort(mContext, "新增/修改成功！");
                getData();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                T.showShort(mContext, "新增失败！" + e.toString());
            }
        });
    }

    public void deleteBookInfosAsync(Product product) {
        if (mCloudDBZone == null) {
            return;
        }

        Task<Integer> deleteTask = mCloudDBZone.executeDelete(product);
        deleteTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                T.showShort(mContext, "删除成功！");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                T.showShort(mContext, "删除失败:" + e.toString());
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(AddEvent event) {
        if (event.getSuccess()) {
            AGConnectUser user = AGConnectAuth.getInstance().getCurrentUser();
            if (user != null) {
                Product mProduct = event.getmProduct();
                maxId = maxId + 1;
                mProduct.setId(maxId);
                upsertProduct(event.getmProduct());
            }
        } else {
            upsertProduct(event.getmProduct());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mCloudDB.closeCloudDBZone(mCloudDBZone);
        } catch (AGConnectCloudDBException e) {
            e.printStackTrace();
        }
        EventBus.getDefault().unregister(this);
    }
}